package phone.stubs;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class PhoneStubLeave {
	public static final String HOST = "localhost";
	public static final int PORT = 8000;
	
	private BufferedReader in;
   	private PrintWriter out;
	
	private Socket socket;
	
	public PhoneStubLeave() {
		try {
			socket = new Socket(HOST, PORT);
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		try {
			out = new PrintWriter(socket.getOutputStream(), true);
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		} catch (IOException e2) {
			System.err.println("Couldn't get I/O connection");
			System.exit(1);
		}    	 
	}
	
	public void send(String message)
	{
		out.println(message);
		System.out.println("PhoneStub sent: " + message);
	}
	
	public String receive() 
	{
		String receivedMessage = "";
		try {
			receivedMessage = in.readLine();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("PhoneStub received: " + receivedMessage);
		
		return receivedMessage;
	}
	
	
	public void close()
	{
		try {
			out.close();
			in.close();
			socket.close();   
		} catch (IOException e) { 
			System.err.println("Couldn't get I/O for the connection");
			System.exit(1);
		}	   
	}
	
	public static void main(String[] args){
		PhoneStubLeave phone = new PhoneStubLeave();
		
		// {"type":11,"gameDetails":{"name":"Player"}}
		// Username entry: "Player"
		phone.send("{\"type\":11,\"gameDetails\":{\"name\":\"Player\"}}");
		
		// {"type":12,"gameDetails":{"name":"Game Server", "password":"123"}}
		// Join game with name "Game Server" and password "123"
		phone.send("{\"type\":13,\"gameDetails\":{\"name\":\"Game Server\", \"password\":\"123\"}}");

		while(true) {
			phone.receive();
			try {
				Thread.sleep(6000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			// Leave
			phone.send("{\"type\":17}");
		}
		// phone.close();
	}
}
